let express=require('express');
let router=express.Router();
let session=require('cookie-session');
let ejs=require('ejs');
let svgcaptcha=require('svg-captcha');
let fs = require("fs");
// 加载persons.json
let persons = fs.readFileSync(__dirname + "/persons.json", "utf8");
// 转换  将字符串转换为对象数组
persons = JSON.parse(persons);
// 渲染主页页面
router.get('/index',(req,res)=>{
    if(req.session.username){
        res.render('index.html',{add:'欢迎'+req.session.username});
    }else{
        res.render('index.html',{add:'请先登录'});
    }
});
// 验证码路由
router.get('/yzm',(req,res)=>{
    let captcha=svgcaptcha.create();
    // console.log(captcha);
    req.session.yzm=captcha.text;
    res.type('svg');
    res.send(captcha.data)
})
// 渲染注册页路由
router.get('/register',(req,res)=>{
    res.render('register.html');
});
// 提交注册页
router.post('/register',(req,res)=>{
    console.log(req.body);
    let {test2,pass2,pass3,yzm2}=req.body;
    let u = persons.findIndex((item, index) => {
        return (item.username == test2) && (item.password == pass2)&&(pass2==pass3)&&(yzm2.toUpperCase()==req.session.yzm.toUpperCase())
    });
    console.log(u);
    if(u==-1){
        // 当persons内不存在该对象时
        req.session.username=test2;
        res.redirect('/login');
    }else{
        res.redirect('/register')
    }
})
// 渲染登录页路由
router.get('/login',(req,res)=>{
    res.render('login.html')
})
// 提交登录页面
router.post('/login',(req,res)=>{
    let {user1,pass1,test1}=req.body;
    console.log(user1,pass1,test1.toUpperCase(),req.session.yzm.toUpperCase());
    let u = persons.find((item, index) => {
        return (item.username == user1 )&& (item.password == pass1) &&(test1.toUpperCase()==req.session.yzm.toUpperCase())
    });
    if (u) {
        req.session.username=user1;
        req.session.password=pass1;
        res.redirect('/index');
        
    } else {
        res.redirect('/login');
      
    }
})
// 错误处理中间件
router.use((req, res) => {
    res.status(404).send("你访问的路由不存在");
})
module.exports=router